package com.guide.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.guide.enums.ErrorCodeEnum;
import com.guide.exception.ServiceException;

public class SmsUtils {
	protected static final Logger logger = LoggerFactory.getLogger(SmsUtils.class);
	
	public static String sendSmsByTP(String desNo,
			String msg) {
		if (StringUtils.isEmpty(desNo) || StringUtils.isEmpty(msg)) {
			throw new ServiceException(ErrorCodeEnum.CODE_GUIDE_SMS_PARAM_ERROR);
		}
		String tpUser = PropertiesUtil.getPropertySys("tp_sms_user");
    	String tpPass = PropertiesUtil.getPropertySys("tp_sms_pass");
    	String tpHost = PropertiesUtil.getPropertySys("tp_host");
    	String tpNs = PropertiesUtil.getPropertySys("tp_ns");
    	String tpChannel = PropertiesUtil.getPropertySys("tp_channel");
		 String batchnumber = "";
		 Map<String,String> param = new HashMap<String,String>();  
		 logger.error("DesNo--->"+desNo);
		 logger.error("Msg--->"+msg);
//		 logger.error(Config.TP_USERCODE);
         param.put("userCode", tpUser);  
         param.put("userPass", tpPass);  
         param.put("DesNo", desNo);  
         param.put("Msg", formatMsg(msg)); 
         param.put("Channel", tpChannel);  
         String method="SendMsg"; 
         String batchNumber="-999";
	
		 try {
			batchNumber = accessService(tpHost,tpNs,method,param,"SendMsgResult");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throwExceptionByTP(batchNumber);
			e.printStackTrace();
		}
		 return batchNumber;
	}
	
	private static void throwExceptionByTP(String batchnum) {
		if (batchnum.equals("-1") ) {
			throw new ServiceException(ErrorCodeEnum.CODE_TP_SMS_INTERFACE_ERROR);
		}else if (batchnum.equals("-3") ) {
			throw new ServiceException(ErrorCodeEnum.CODE_TP_SMS_AUTH_ERROR);
		}else if (batchnum.equals("-4") ) {
			throw new ServiceException(ErrorCodeEnum.CODE_TP_SMS_TEMPLATE_ERROR);
		}else if (batchnum.equals("-5") ) {
			throw new ServiceException(ErrorCodeEnum.CODE_TP_SMS_SIGN_ERROR);
		}else if (batchnum.equals("-7") ) {
			throw new ServiceException(ErrorCodeEnum.CODE_TP_SMS_BALANCE_ERROR);
		}else if (batchnum.equals("-8") ) {
			throw new ServiceException(ErrorCodeEnum.CODE_TP_SMS_CHANNEL_ERROR);
		}else if (batchnum.equals("-9") ) {
			throw new ServiceException(ErrorCodeEnum.CODE_TP_SMS_INVALID_NUM_ERROR);
		}else if (batchnum.equals("-999") ) {
			throw new ServiceException(ErrorCodeEnum.SYSTEM_ERROR);
		}
	}
	
	private static String formatMsg(String msg) {
		if (StringUtils.isEmpty(msg)) {
			throw new ServiceException(ErrorCodeEnum.SYSTEM_PARAMS_ERROR);
		}
		String msgTmp = msg.replaceAll("[\\t\\n\\r]", "").trim();
		if(msgTmp.endsWith("【约导游】")){
			return msgTmp;
		}else {
			return msgTmp+"【约导游】";
		}
		
	}
	
	public static  String accessService(String wsdl,String ns,String method,Map<String,String> params,String result)throws Exception{  
        //拼接参数  
        String param = getParam(params);  
        String soapResponseData = "";  
        //拼接SOAP  
        StringBuffer soapRequestData = new StringBuffer("");  
        soapRequestData.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        soapRequestData.append("<soap:Envelope "+
        		               "xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" " +
        		               " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" " +
        		               "xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " +
        		               " >");
        soapRequestData.append("<soap:Body>");  
        soapRequestData.append("<"+method+" xmlns=\""+ns+"\">");  
        soapRequestData.append(param);  
        soapRequestData.append("</"+method+">");  
        soapRequestData.append("</soap:Body>" + "</soap:Envelope>"); 
        
        DefaultHttpClient httpClient = new DefaultHttpClient();
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
        // 读取超时
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);
        HttpPost httpPost = new HttpPost(wsdl);
        // 然后把Soap请求数据添加到PostMethod中  
        byte[] b=null;  
        InputStream is=null; 
        try {  
            b = soapRequestData.toString().getBytes("utf-8");   
            is = new ByteArrayInputStream(b, 0, b.length);  
            InputStreamEntity ise = new InputStreamEntity(is, b.length,ContentType.create("application/soap+xml", "utf-8"));
//        	System.out.println(soapRequestData.toString());
        	httpPost.setEntity(ise);
        	HttpResponse httpResponse = httpClient.execute(httpPost);
			int status = httpResponse.getStatusLine().getStatusCode();
            System.out.println("status:"+status);  
            if(status==200){  
            	String ret = getResponseMsg(httpResponse.getEntity().getContent());
            	logger.error("ret--->"+ret);
            	soapResponseData = getMesage(ret, result);
            	System.out.println("result:---> " + soapResponseData);
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally{  
            if(is!=null){  
                is.close();  
            }  
        }  
        return soapResponseData;  
    }  
	
	public static String getParam(Map<String,String> params){  
        String param = "";  
        if(params!=null){  
            Iterator<String> it  = params.keySet().iterator();  
            while(it.hasNext()){  
                String str = it.next();  
                param+="<"+str+">";  
                param+=params.get(str);  
                param+="</"+str+">";  
            }  
        }  
        return param;  
    }  
	
	public static String getMesage(String soapAttachment,String result){  
		logger.error("response:"+soapAttachment);  
        if(result==null){  
            return null;  
        }  
        if(soapAttachment!=null && soapAttachment.length()>0){  
            int begin = soapAttachment.indexOf(result);  
            begin = soapAttachment.indexOf(">", begin);  
            int end = soapAttachment.indexOf("</"+result+">");  
            String str = soapAttachment.substring(begin+1, end);  
//            str = str.replaceAll("<", "<");  
//            str = str.replaceAll(">", ">");  
            return str;  
        }else{  
            return "";  
        }  
    }  
	
	public static String getResponseMsg(InputStream re) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(re));
		StringBuilder builder = new StringBuilder();
		String data = null;
		while((data = reader.readLine()) != null) {
			builder.append(data).append(" ");
		}
		reader.close();
		return builder.toString();
	}
}
